package com.lzw.breezeNovel.webApp.service.impl.video;

import com.lzw.breezeNovel.common.exception.BaseException;
import com.lzw.breezeNovel.common.login.LoginUser;
import com.lzw.breezeNovel.common.login.LoginUserHolder;
import com.lzw.breezeNovel.common.result.ResultCodeEnum;
import com.lzw.breezeNovel.model.entity.pojo.user.UserInfo;
import com.lzw.breezeNovel.model.entity.pojo.video.PlayRecord;
import com.lzw.breezeNovel.webApp.mapper.user.UserInfoMapper;
import com.lzw.breezeNovel.webApp.mapper.video.PlayRecordMapper;
import com.lzw.breezeNovel.webApp.service.video.PlayRecordService;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.impl.video
 * @date 2025/3/19
 * @description
 */
@Service
@SuppressWarnings("all")
public class PlayRecordServiceImpl implements PlayRecordService {
    /**
     * 注入mapper
     */
    @Autowired
    private PlayRecordMapper playRecordMapper;
    /**
     * 注入用户mapper
     */
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 添加播放记录
     * @param playRecord
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addPlayRecord(@NotNull PlayRecord playRecord) {
        //获取当前用户
        Long userId = getUserId();
        playRecord.setUserId(userId);
        //根据用户id查浏览记录
        PlayRecord p = playRecordMapper.selectByUserIdAndVideoId(playRecord);
        //判断是否存在
        if (p != null){
            //存在则更新
            playRecordMapper.updateById(playRecord);
        }else
        {
            //设置时间
            playRecord.setPlayTime(new Date());
            //不存在则添加
            playRecordMapper.insert(playRecord);
        }

    }

    /**
     * 获取播放记录
     *
     * @param voideId
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public PlayRecord getPlayRecord(@NotNull PlayRecord playRecord) {
        //获取当前用户
        Long userId = getUserId();
        //设置用户id
        playRecord.setUserId(userId);
        //根据用户id和视频id查询播放记录
        return playRecordMapper.selectByUserIdAndVideoId(playRecord);
    }

    /**
     * 获取当前用户
     */
    @Nullable
    @Contract(pure = true)
    private Long getUserId(){
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        if (loginUser == null){
            throw new BaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        String phone = loginUser.getPhone();
        //根据手机号查询用户id
        UserInfo userInfo = userInfoMapper.selectByPhone(phone);
        return userInfo.getUserId();
    }
}
